package com.zggk.lzz.gj;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.trace.LBSTraceClient;
import com.amap.api.trace.TraceListener;
import com.amap.api.trace.TraceLocation;
import com.blankj.utilcode.util.ToastUtils;
import com.zggk.lzz.R;
import com.zggk.lzz.mvp.MVPBaseActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class GJActivity extends MVPBaseActivity<GJContract.View, GJPresenter> implements GJContract.View, AMap.OnMapLoadedListener {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.map)
    MapView mMapView;
    @Bind(R.id.xcrq_te)
    TextView xcrqTe;
    @Bind(R.id.xcry_te)
    TextView xcryTe;
    private AMap mAMap;
    private final static int AMAP_LOADED = 2;

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_gj;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();
    }

    private void initMap() {
        xcrqTe.setText(getIntent().getStringExtra("time"));
        xcryTe.setText(getIntent().getStringExtra("xcr"));
        setTitleText("巡查轨迹");
        goBack();
        if (mAMap == null) {
            mAMap = mMapView.getMap();
            mAMap.setOnMapLoadedListener(this);
            mAMap.getUiSettings().setRotateGesturesEnabled(false);
            mAMap.getUiSettings().setTiltGesturesEnabled(false);
        }
    }

    @Override
    public void onMapLoaded() {
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    mPresenter.getLinDatas(getIntent().getStringExtra("id"), GJActivity.this);
                    mPresenter.getLinDatas2(getIntent().getStringExtra("id"));
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void getLinDatass(final List<GJBean.DataBean> JWD) {
        if (JWD.size() > 2) {
            List<TraceLocation> mGraspTraceLocationList = readLatLngs(JWD);
            LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
            mTraceClient.queryProcessedTrace(1, mGraspTraceLocationList,
                    LBSTraceClient.TYPE_AMAP, new TraceListener() {
                        @Override
                        public void onRequestFailed(int i, String s) {
                            Log.e("测试纠偏","111"+s);
                            List<LatLng> points = readLatLngss(JWD);
                            mAMap.addPolyline(new PolylineOptions()
                                    .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.grasp_trace_line))
                                    .width(30).addAll(points));
                            mAMap.addMarker(new MarkerOptions().position(
                                    points.get(0)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.start2)));
                            mAMap.addMarker(new MarkerOptions().position(
                                    points.get(points.size() - 1)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.end)));
                        }

                        @Override
                        public void onFinished(int i, List<LatLng> list, int i1, int i2) {
                            Log.e("测试纠偏","222");
                            mAMap.addPolyline(new PolylineOptions()
                                    .setCustomTexture(BitmapDescriptorFactory.fromResource(R.drawable.grasp_trace_line))
                                    .width(30).addAll(list));
                            LatLngBounds.Builder b = LatLngBounds.builder();
                            for (int x = 0; x < list.size(); x++) {
                                b.include(list.get(i));
                            }
                            mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(b.build(),
                                    50));
                            mAMap.addMarker(new MarkerOptions().position(
                                    list.get(0)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.start2)));
                            mAMap.addMarker(new MarkerOptions().position(
                                    list.get(list.size() - 1)).icon(
                                    BitmapDescriptorFactory.fromResource(R.drawable.end)));
                        }

                        @Override
                        public void onTraceProcessing(int i, int i1, List<LatLng> list) {
                        }

                    });
        }else {
            ToastUtils.showShort("该条巡查记录没有轨迹信息！");
        }
    }

    @Override
    public void getLinDatass2(List<List<GJ2Bean.DataBean>>  datas) {
        for (int i = 0; i < datas.size(); i++) {
            List<GJ2Bean.DataBean> JWD =new ArrayList<>();
            JWD.addAll(datas.get(i));
            setRoad(JWD);
        }
    }
    private void setRoad(final List<GJ2Bean.DataBean> JWD) {
        if (JWD.size() > 2) {
            List<TraceLocation> mGraspTraceLocationList = readLatLngs2(JWD);
            LBSTraceClient mTraceClient = new LBSTraceClient(getApplicationContext());
            mTraceClient.queryProcessedTrace(1, mGraspTraceLocationList,
                    LBSTraceClient.TYPE_AMAP, new TraceListener() {
                        @Override
                        public void onRequestFailed(int i, String s) {
                            List<LatLng> points = new ArrayList<>();
                            points.add(new LatLng(Double.parseDouble(JWD.get(i).getLat()), Double.parseDouble(JWD.get(i).getLon())));
                            mAMap.addPolyline(new PolylineOptions().color(
                                    Color.RED).width(40).addAll(points));
                        }
                        @Override
                        public void onFinished(int i, List<LatLng> list, int i1, int i2) {
                            mAMap.addPolyline(new PolylineOptions().color(
                                    Color.RED).width(40).addAll(list));
                        }
                        @Override
                        public void onTraceProcessing(int i, int i1, List<LatLng> list) {
                        }
                    });
        }else {
            ToastUtils.showShort("该条巡查记录没有轨迹信息！");
        }
    }

    private List<TraceLocation> readLatLngs(List<GJBean.DataBean> JWD) {
        CoordinateConverter converter = new CoordinateConverter(getContext());
        List<TraceLocation> mGraspTraceLocationList = new ArrayList<>();
        for (int i = 0; i < JWD.size(); i++) {
                boolean isAMapDataAvailable = converter.isAMapDataAvailable(Double.parseDouble(JWD.get(i).getJWData().getLat()), Double.parseDouble(JWD.get(i).getJWData().getLon()));
                if (isAMapDataAvailable) {
                    TraceLocation location = new TraceLocation();
                    location.setBearing(0);
                    location.setLatitude(Double.parseDouble(JWD.get(i).getJWData().getLat()));
                    location.setLongitude(Double.parseDouble(JWD.get(i).getJWData().getLon()));
                    location.setSpeed(0);
                    location.setTime(0);
                    mGraspTraceLocationList.add(location);
                }
        }
        return mGraspTraceLocationList;
    }
    private List<TraceLocation> readLatLngs2(List<GJ2Bean.DataBean> JWD) {
        CoordinateConverter converter = new CoordinateConverter(getContext());
        List<TraceLocation> mGraspTraceLocationList = new ArrayList<>();
        for (int i = 0; i < JWD.size(); i++) {
            boolean isAMapDataAvailable = converter.isAMapDataAvailable(Double.parseDouble(JWD.get(i).getLat()), Double.parseDouble(JWD.get(i).getLon()));
            if (isAMapDataAvailable) {
                TraceLocation location = new TraceLocation();
                location.setBearing(0);
                location.setLatitude(Double.parseDouble(JWD.get(i).getLat()));
                location.setLongitude(Double.parseDouble(JWD.get(i).getLon()));
                location.setSpeed(0);
                location.setTime(0);
                mGraspTraceLocationList.add(location);
            }
        }
        return mGraspTraceLocationList;
    }
    private List<LatLng> readLatLngss(List<GJBean.DataBean> JWD) {
        List<LatLng> points = new ArrayList<>();
        LatLngBounds.Builder b = LatLngBounds.builder();
        for (int i = 0; i < JWD.size(); i++) {
                points.add(new LatLng(Double.parseDouble(JWD.get(i).getJWData().getLat()), Double.parseDouble(JWD.get(i).getJWData().getLon())));
                b.include(points.get(i));
        }
        mAMap.moveCamera(CameraUpdateFactory.newLatLngBounds(b.build(),
                50));
        return points;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

}
